package cn.cas.mango.util.keywordsBatch;
import cn.cas.mango.util.dbscan.Data;

import java.util.*;
public class KeywordClustering {


  public static Map<String, List<String>> clusterIdsByKeywords(Map<String, List<String>> keywordToIds) {
    Set<String> allIds = new HashSet<>();
    for (List<String> ids : keywordToIds.values()) {
      allIds.addAll(ids);
    }

    UnionFind unionFind = new UnionFind(allIds);

    for (List<String> ids : keywordToIds.values()) {
      for (int i = 1; i < ids.size(); i++) {
        unionFind.union(ids.get(0), ids.get(i));
      }
    }
    return unionFind.getClusters();
  }
  public static List<List<Data>> getBatchData(List<Data> dataList) {
    Map<String, List<String>> clusterData = new KeywordsCast(dataList).getClusterData();
    clusterData = clusterIdsByKeywords(clusterData);
    Map<String, List<Data>> idToData = new HashMap<>();
    for (Data data : dataList) {
      String id = data.getId();
      if (!idToData.containsKey(id)) {
        idToData.put(id, new ArrayList<>());
      }
      idToData.get(id).add(data);
    }
    List<List<Data>> ret = new ArrayList<>();
    for (List<String>ids: clusterData.values()) {
      List<Data> cluster = new ArrayList<>();
      for (String id : ids) {
        cluster.addAll(idToData.get(id));
      }
      ret.add(cluster);
    }
    return ret;
  }




  public static void main(String[] args) {
    Map<String, List<String>> keywordToIds = new HashMap<>();
    keywordToIds.put("java", Arrays.asList("id1", "id2", "id4"));
    keywordToIds.put("spring", Arrays.asList("id1", "id5"));
    keywordToIds.put("hibernate", Arrays.asList("id2"));
    keywordToIds.put("python", Arrays.asList("id3", "id6"));
    keywordToIds.put("flask", Arrays.asList("id4", "id6"));
    keywordToIds.put("django", Arrays.asList("id3"));
    keywordToIds.put("security", Arrays.asList("id5"));

    Map<String, List<String>> clusters = clusterIdsByKeywords(keywordToIds);

    for (Map.Entry<String, List<String>> entry : clusters.entrySet()) {
      System.out.println("Cluster root: " + entry.getKey() + " -> IDs: " + entry.getValue());
    }
  }
}
